package com.cskaoyan.wx.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.wx.bean.bo.WxCartAddBo;
import com.cskaoyan.wx.bean.bo.WxCartCheckBo;
import com.cskaoyan.wx.bean.bo.WxCartDeleteBo;
import com.cskaoyan.wx.bean.bo.WxCartUpdateBo;
import com.cskaoyan.wx.bean.vo.WxCartCheckoutVo;
import com.cskaoyan.wx.bean.vo.WxCartIndexVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class WxCartServicelmpl implements  WxCartService {

    private Integer goodsId;
    private Integer productId;
    private Integer temp = 0;//立即购买辅助变量
    private Integer userId;

    @Autowired
    CartMapper cartMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ConfigMapper configMapper;

    /**
     * 功能:购物车页面,/index
     * 作者:whj
     */
    @Override
    public WxCartIndexVo query() {
        usernameToId();
        WxCartIndexVo cartIndexVo = new WxCartIndexVo();
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        cartIndexVo.setCartList(carts);
        WxCartIndexVo.CartTotalBean cartTotal = new WxCartIndexVo.CartTotalBean();
        cartTotal.setGoodsCount(carts.size());
        double goodsAmout = 0;
        double checkedGoodsAmount = 0;
        int checkedGoodsCount = 0;
        for (Cart cart : carts) {
            double price = cart.getPrice().doubleValue();
            goodsAmout = goodsAmout + price * cart.getNumber();
            if(cart.getChecked()){
                checkedGoodsAmount = checkedGoodsAmount + price * cart.getNumber();
                checkedGoodsCount ++;
            }
        }
        cartTotal.setCheckedGoodsCount(checkedGoodsCount);
        cartTotal.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotal.setGoodsAmount(goodsAmout);
        cartIndexVo.setCartTotal(cartTotal);
        return cartIndexVo;
    }

    private void usernameToId() {
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        //根据username获取用户其他信息
        UserExample userExample = new UserExample();
        UserExample.Criteria userExampleCriteria = userExample.createCriteria();
        userExampleCriteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        userId = users.get(0).getId();
    }

    /**
     * 功能:购物车页面,/checked
     * 作者:whj
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED)
    @Override
    public WxCartIndexVo checked(WxCartCheckBo wxCartCheckBo) {
        usernameToId();
        WxCartIndexVo cartIndexVo = new WxCartIndexVo();
        //根据用户id,productIds改变isChecked的状态
        List<Integer> productIds = wxCartCheckBo.getProductIds();
        Cart checkedBo = new Cart();
        if(wxCartCheckBo.getIsChecked() == 1){
            checkedBo.setChecked(true);
        }else {
            checkedBo.setChecked(false);
        }
        checkedBo.setUserId(userId);
        for (Integer productId : productIds) {
            checkedBo.setProductId(productId);
            int code = cartMapper.updateIsCheckedByProductIds(checkedBo);
            if(code == 0){
                return null;
            }
        }
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        cartIndexVo.setCartList(carts);
        WxCartIndexVo.CartTotalBean cartTotal = new WxCartIndexVo.CartTotalBean();
        cartTotal.setGoodsCount(carts.size());
        double goodsAmout = 0;
        double checkedGoodsAmount = 0;
        int checkedGoodsCount = 0;
        for (Cart cart : carts) {
            double price = cart.getPrice().doubleValue();
            goodsAmout = goodsAmout + price * cart.getNumber();
            if(cart.getChecked()){
                checkedGoodsAmount = checkedGoodsAmount + price * cart.getNumber();
                checkedGoodsCount ++;
            }
        }
        cartTotal.setCheckedGoodsCount(checkedGoodsCount);
        cartTotal.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotal.setGoodsAmount(goodsAmout);
        cartIndexVo.setCartTotal(cartTotal);
        return cartIndexVo;
    }

    /**
     * 功能:购物车页面,/update
     * 作者:whj
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED)
    @Override
    public int update(WxCartUpdateBo wxCartUpdateBo) {
        usernameToId();
        Cart cart = new Cart();
        cart.setId(wxCartUpdateBo.getId());
        Short number = Short.valueOf(wxCartUpdateBo.getNumber().toString());
        cart.setNumber(number);
        cart.setGoodsId(wxCartUpdateBo.getGoodsId());
        cart.setProductId(wxCartUpdateBo.getProductId());
        cart.setUpdateTime(new Date(System.currentTimeMillis()));
        int code = cartMapper.updateByPrimaryKeySelective(cart);
        if(code == 0){
            return 404;
        }
        return 200;
    }

    /**
     * 功能:购物车页面,/delete
     * 作者:whj
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED)
    @Override
    public WxCartIndexVo delete(WxCartDeleteBo wxCartDeleteBo) {
        usernameToId();
        WxCartIndexVo cartIndexVo = new WxCartIndexVo();
        List<Integer> productIds = wxCartDeleteBo.getProductIds();
        //根据用户id,productIds改变deleted的状态
        Cart deleteBo = new Cart();
        deleteBo.setUserId(userId);
        deleteBo.setUpdateTime(new Date(System.currentTimeMillis()));
        for (Integer productId : productIds) {
            deleteBo.setProductId(productId);
            int code = cartMapper.updateDeletedAndUpdateTimeByProductIdsAndUserId(deleteBo);
            if(code == 0){
                return null;
            }
        }
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        cartIndexVo.setCartList(carts);
        WxCartIndexVo.CartTotalBean cartTotal = new WxCartIndexVo.CartTotalBean();
        cartTotal.setGoodsCount(carts.size());
        double goodsAmout = 0;
        double checkedGoodsAmount = 0;
        int checkedGoodsCount = 0;
        for (Cart cart : carts) {
            double price = cart.getPrice().doubleValue();
            goodsAmout = goodsAmout + price * cart.getNumber();
            if(cart.getChecked()){
                checkedGoodsAmount = checkedGoodsAmount + price * cart.getNumber();
                checkedGoodsCount ++;
            }
        }
        cartTotal.setCheckedGoodsCount(checkedGoodsCount);
        cartTotal.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotal.setGoodsAmount(goodsAmout);
        cartIndexVo.setCartTotal(cartTotal);
        return cartIndexVo;
    }

    /**
     * 功能:购物车页面,/checkout
     * 作者:whj
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED)
    @Override
    public WxCartCheckoutVo checkout(Integer cartId, Integer addressId, Integer couponId, Integer grouponRulesId) {
        usernameToId();
        WxCartCheckoutVo checkoutVo = new WxCartCheckoutVo();
        //忽略团购信息,相关信息置为0
        checkoutVo.setGrouponPrice(0);
        checkoutVo.setGrouponRulesId(grouponRulesId);
        //根据addressId,查找收货人信息
        Address address = addressMapper.selectByPrimaryKey(addressId);
        checkoutVo.setCheckedAddress(address);
        //根据userId,checked=true,deleted=false,获取checkedGoodsList
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        //如果cartId=228,获取立即购买的godsId,productId
        if(cartId == 228){
            criteria.andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false)
                    .andGoodsIdEqualTo(goodsId).andProductIdEqualTo(productId);
        }else {
            criteria.andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        }
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        checkoutVo.setCheckedGoodsList(carts);
        checkoutVo.setAddressId(addressId);
        double goodsTotalPrice = 0;
        for (Cart cart : carts) {
            double price = cart.getPrice().doubleValue();
            goodsTotalPrice = goodsTotalPrice + cart.getNumber() * price;
        }
        checkoutVo.setGoodsTotalPrice(goodsTotalPrice);
        //根据userId,获取AvailableCouponLength
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria couponUserExampleCriteria = couponUserExample.createCriteria();
        couponUserExampleCriteria.andUserIdEqualTo(userId);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        checkoutVo.setAvailableCouponLength(couponUsers.size());
        //根据用户couponId,获取couponPrice
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
        double couponPrice = 0;
        if(coupon ==null){
            checkoutVo.setCouponPrice(0);
        }else {
            couponPrice = coupon.getDiscount().doubleValue();
            checkoutVo.setCouponPrice(couponPrice);
        }
        double orderTotalPrice = goodsTotalPrice - couponPrice;
        checkoutVo.setOrderTotalPrice(orderTotalPrice);

        //根据运费配置,设定运费
        List<Map> express_freight_min = configMapper.selectMallConfig("express_freight_min");
        List<Map> express_freight_value = configMapper.selectMallConfig("express_freight_value");
        Collection values = express_freight_min.get(0).values();
        Collection values1 = express_freight_value.get(0).values();
        Integer freightPrice = 0;
        for (Object value : values) {
            Integer min = Integer.parseInt(value.toString());
            if(orderTotalPrice < min){
                for (Object o : values1) {
                    String prince = (String) o;
                    freightPrice = Integer.parseInt(prince);
                    break;
                }
            }
            break;
        }
        checkoutVo.setCouponId(-1);
        checkoutVo.setFreightPrice(freightPrice);
        double actualPrice = orderTotalPrice + freightPrice;
        checkoutVo.setActualPrice(actualPrice);
        return checkoutVo;
    }

    /**
     * 功能:加入购物车,/add
     * 作者:whj
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED)
    @Override
    public int add(WxCartAddBo wxCartAddBo) {
        usernameToId();
        Cart cart = new Cart();
        //根据goodsId获取商品信息
        int goodsId = wxCartAddBo.getGoodsId();
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        cart.setUserId(userId);
        cart.setGoodsId(goodsId);
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName(goods.getName());
        //根据productId获取规格信息
        int productId = wxCartAddBo.getProductId();
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
        cart.setProductId(productId);
        cart.setPrice(goodsProduct.getPrice());
        cart.setNumber(wxCartAddBo.getNumber());
        cart.setSpecifications(goodsProduct.getSpecifications());
        cart.setChecked(true);
        cart.setPicUrl(goodsProduct.getUrl());
        Date date = new Date(System.currentTimeMillis());
        cart.setAddTime(date);
        cart.setUpdateTime(date);
        cart.setDeleted(false);
        //如果userId,goodsId,productId相同即合并
        CartExample cartExample1 = new CartExample();
        CartExample.Criteria criteria1 = cartExample1.createCriteria();
        criteria1.andUserIdEqualTo(userId).andGoodsIdEqualTo(goodsId).andProductIdEqualTo(productId).andDeletedEqualTo(false);
        List<Cart> carts1 = cartMapper.selectByExample(cartExample1);
        int code = -1;
        if(carts1.size() != 0){
            //立即购买
            if(temp == 228){
                cart.setNumber(wxCartAddBo.getNumber());
            }else {
                //加入购物车
                Integer number = carts1.get(0).getNumber() + wxCartAddBo.getNumber();
                Short aShort = Short.valueOf(number.toString());
                cart.setNumber(aShort);
            }
            code = cartMapper.updateByExampleSelective(cart, cartExample1);
        }else {
            code = cartMapper.insert(cart);
        }
        if(code == 0){
            return -1;
        }
        //根据userId,delected查询购物车数量
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        temp = 0;//立即购买辅助变量
        //调用goodscount,更新购物车图标
        int goodscount = goodscount();
        return goodscount;
        //return carts.size();
    }

    /**
     * 功能:购物车商品数量,/goodscount
     * 作者:whj
     */
    @Override
    public int goodscount() {
        usernameToId();
        //根据userId,delected查询购物车数量
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        Integer count = 0;
        for (Cart cart : carts) {
            count = count + cart.getNumber();
        }
        return count;
    }

    /**
     * 功能:购物车商品数量,/fastadd
     * 作者:whj
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED)
    @Override
    public int fastadd(WxCartAddBo wxCartAddBo) {
        usernameToId();
        //立即购买也要加入购物车
        temp = 228;
        add(wxCartAddBo);
        //根据goodsId和productId获取规格信息
        goodsId = wxCartAddBo.getGoodsId();
        productId = wxCartAddBo.getProductId();
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria criteria = goodsProductExample.createCriteria();
        criteria.andGoodsIdEqualTo(wxCartAddBo.getGoodsId()).andIdEqualTo(wxCartAddBo.getProductId());
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        //productId必定只有一个
        Integer number = goodsProducts.get(0).getNumber();
        if(number-wxCartAddBo.getNumber() < 0){
            return -1;
        }
        return number-wxCartAddBo.getNumber();
    }



}
